/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helper;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author Hallucinogen
 */
public class Utilities {
    public static String getValueFromHTTPGetURL(String URL, String inpKey){
        String key = inpKey.toLowerCase();
        StringBuilder res = new StringBuilder();

        URL = "?" + URL;

        String mKey = "?" + key;
        int pos = URL.indexOf(mKey);

        if (pos == -1) {
            mKey = "&" + key;
            pos = URL.indexOf(mKey);

            if (pos == -1)
                return res.toString();
        }

        pos += mKey.length() + 1;

        char c;
        while (pos < URL.length() &&(c = URL.charAt(pos)) != '&') {
            res.append(c);
            ++pos;
        }

        return res.toString();
    }

    public static byte[] getByteArrayFromFile(File file){
        if (file.length() > Integer.MAX_VALUE) return null;
        
        byte[] bytes = new byte[(int)file.length()];

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);

            bis.read(bytes);

            bis.close();
            fis.close();
        } catch (IOException ex) {
            
        } finally {
            
        }
        
        return bytes;
    }

    public static String convertToSHA1(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException{
        return convertToSHA1(input.getBytes("iso-8859-1"));
    }

    public static String convertToSHA1(byte[] input) throws NoSuchAlgorithmException{
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(input);
        byte[] sha1hash = md.digest();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < sha1hash.length; i++) {
          sb.append(Integer.toString((sha1hash[i] & 0xff) + 0x100, 16).substring(1));
        }

        return sb.toString();
    }

    public static String TRACKER_HOST           = "192.168.1.102";
    public static int TRACKER_PORT              = 1234;
    public static int PEER_PORT                 = 12345;
    public static int INTERVAL                  = 3000;
    public static int PEER_REQUEST_INTERVAL     = 2000;
    //public static int PEER_DOWNLOAD_INTERVAL    = 120000;
    public static int KEEP_ALIVE                = 120000;
    public static String DEFAULT_PROTOCOL       = "BitTorrent protocol";
}
